package com.cyf.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
public class WebSocketUtils {
	private static final Logger logger = LoggerFactory
			.getLogger(WebSocketUtils.class);

	public static boolean isConnected(WebSocketSession session) {
		if (session != null && session.isOpen()) {
			return true;
		}
		return false;
	}

	public static void sendMessage(WebSocketSession session, Object obj) {
		if (isConnected(session)) {
			logger.info("准备向{}发送数据{}......", session.getLocalAddress(), obj);
			try {
				ObjectMapper req = new ObjectMapper();
				String str = req.writeValueAsString(obj);
				TextMessage message = new TextMessage(str.getBytes("utf-8"));
				session.sendMessage(message);
				logger.info("数据{}发送到{}成功......", obj,
						session.getLocalAddress());
			} catch (Exception e) {
				logger.error("数据"+ obj +"发送"+session.getLocalAddress() + "到云端异常：{}", e);
			}
		} else {
			logger.info("数据{}发送异常：{}", obj, "连接失效，session空或已经关闭");
		}
	}
}
